import { CheckOutlined } from "@ant-design/icons";
import { Button, List, Tag, theme } from "antd";
import { useEffect, useState } from "react";
import notificationService from "@/api/services/notification";

interface Notification {
	id: string;
	title: string;
	content: string;
	createtime: number;
	status: "read" | "unread";
}

export const NotificationList = () => {
	const [notifications, setNotifications] = useState<Notification[]>([]);
	const [loading, setLoading] = useState(false);
	const [unreadCount, setUnreadCount] = useState(0);
	const { token: themeToken } = theme.useToken();

	const fetchNotifications = async () => {
		try {
			setLoading(true);
			const response = await notificationService.notificationList({
				page: 1,
				limit: 10,
			});
			setNotifications(response.data);
			setUnreadCount(
				response.data.filter((n: any) => n.status === "unread").length,
			);
		} catch (error) {
			console.error("Failed to fetch notifications:", error);
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		fetchNotifications();
	}, []);

	const handleMarkAllRead = () => {
		setUnreadCount(0);
		// TODO: 调用标记所有已读的 API
	};

	const getStatusTag = (status: string) => {
		if (status === "unread") {
			return (
				<Tag color="blue" style={{ borderRadius: 10 }}>
					未读
				</Tag>
			);
		}
		return (
			<Tag color="green" icon={<CheckOutlined />} style={{ borderRadius: 10 }}>
				已读
			</Tag>
		);
	};

	return (
		<div className="p-4">
			<div className="flex justify-between items-center mb-4">
				<h3 className="text-lg font-medium m-0">通知列表</h3>
				<Button type="link" onClick={handleMarkAllRead}>
					全部标记为已读
				</Button>
			</div>
			<List
				dataSource={notifications}
				loading={loading}
				renderItem={(item: any) => (
					<List.Item
						className="cursor-pointer hover:bg-gray-50 transition-colors"
						style={{
							padding: "12px",
							borderRadius: themeToken.borderRadius,
						}}
					>
						<List.Item.Meta
							title={
								<div className="flex justify-between items-center">
									<span>{item.title}</span>
									{getStatusTag(item.status)}
								</div>
							}
							description={
								<div className="text-gray-500 mt-2">
									<div>{item.content}</div>
									<div className="text-xs mt-2">
										{new Date(item.createtime).toLocaleString()}
									</div>
								</div>
							}
						/>
					</List.Item>
				)}
			/>
		</div>
	);
};
